﻿using DLL.NET.ComPort;

using DLL.NET50.SerialPort.MCU.LED;
using DLL.NET70.Infrastructure.Prism;
using DLL.NET70.Infrastructure.Prism.MVVM;
using DLL.Standard.Infrastructure.Log;
using Module.NetCore.Commonly.Views;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Module.ExternalDevice.MCU.LED.ViewModels
{
    public class McuControlLedViewModel : CMVVMBase, IRegionMemberLifetime
    {
        private IRegionManager _regionManager;
        private IContainerExtension _container;
        private IControlLED cLed;

        public McuControlLedViewModel(IRegionManager regionManager,
            IEventAggregator ea,
            IApplicationCommands applicationCommands,
            IContainerExtension container,
            IControlLED controlLED
            ) : base(regionManager, ea, applicationCommands)
        {
            Title = "指示灯";
            _container = container;
            _regionManager = regionManager;
            cLed = controlLED;
            try
            {
                cb_ComNameSelectedChangedCommand = new DelegateCommand(CB_ComNameSelectedChanged);
                cb_BaudRateSelectedChangedCommand = new DelegateCommand(cb_BaudRateSelectedChanged);
            }
            catch (Exception e)
            {
                LogHelper.Warn("PUC_OpenComViewModel:" + e.Message);
            }

            #region mcu control led commmand

            ReadAdressCommand = new DelegateCommand(ReadAdress).ObservesCanExecute(() => ComIsEnabled);
            WriteAdressCommand = new DelegateCommand(WriteAdress).ObservesCanExecute(() => ComIsEnabled);
            Initialize();

            #endregion mcu control led commmand
        }

        public bool KeepAlive
        {
            get
            {
                //return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
                return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
            }
        }

        #region private variable

        private static byte MaxCol = 8;
        private static byte MaxRow = 6;
        private byte[,] LED = new byte[MaxRow, MaxCol];
        //private CControlLED cLed = new CControlLED();

        #endregion private variable

        #region windows load

        public override void Loaded()
        {
            RegisterSaveCommand();
            InitializeCom();
            cLed.ReadDeviceID();
            cLed.ReadComParam();
            ComName = settings.cSerialEntity.PortName;
            BaudRate = settings.cSerialEntity.BaudRate;
            base.Loaded();
        }

        public override void UnLoaded()
        {
            UnRegisterSaveCommand();
            CloseCom();
            base.UnLoaded();
        }

        public override void Save()
        {
            cLed.reDeviceID = DeviceAdress;
            cLed.SaveDeviceID();
            SaveCom();
            LogMessage("参数保存成功！");
        }

        #endregion windows load

        #region Com name   Process

        private bool _ComIsEnabled = false;

        public bool ComIsEnabled
        {
            get { return _ComIsEnabled; }
            set
            {
                SetProperty(ref _ComIsEnabled, value);
            }
        }

        private bool _OpenComEnabled = true;

        public bool OpenComEnabled
        {
            get { return _OpenComEnabled; }
            set
            {
                SetProperty(ref _OpenComEnabled, value);
            }
        }

        private SerialSetting settings = new SerialSetting();

        //CComBase comBase ;
        private void InitializeCom()
        {
            try
            {
                #region com command
                cLed.SerialPortManager.CurrentSerialSettings.UpdatePortName();
                //串口名称
                settings = cLed.SerialPortManager.CurrentSerialSettings;
                ComNames = settings.PortNameCollection;
                BaudRates = settings.BaudRateCollection;

                #endregion com command
            }
            catch (Exception e)
            {
                LogHelper.Warn("PUC_OpenComViewModel:" + e.Message);
            }
        }

        private string _comName = "COM1";

        public string ComName
        {
            get { return _comName; }
            set { SetProperty(ref _comName, value); }
        }

        //ComNames
        private string[] _comNames;

        public string[] ComNames
        {
            get { return _comNames; }
            set { SetProperty(ref _comNames, value); }
        }

        private object _cb_ComNameSelectItem;

        public object cb_ComNameSelectItem
        {
            get { return _cb_ComNameSelectItem; }
            set { SetProperty(ref _cb_ComNameSelectItem, value); }
        }

        public int _BaudRate = 9600;

        public int BaudRate
        {
            get { return _BaudRate; }
            set { SetProperty(ref _BaudRate, value); }
        }

        private BindingList<int> _baudRates = new BindingList<int>();

        public BindingList<int> BaudRates
        {
            get { return _baudRates; }
            set { SetProperty(ref _baudRates, value); }
        }

        private object _cb_BaudRateSelectItem;

        public object cb_BaudRateSelectItem
        {
            get { return _cb_BaudRateSelectItem; }
            set { SetProperty(ref _cb_BaudRateSelectItem, value); }
        }

        public DelegateCommand cb_ComNameSelectedChangedCommand { get; private set; }

        private void CB_ComNameSelectedChanged()
        {
            if (cb_ComNameSelectItem != null)
            {
                ComName = cb_ComNameSelectItem.ToString();
                settings.cSerialEntity.PortName = ComName;
            }
        }

        public DelegateCommand cb_BaudRateSelectedChangedCommand { get; private set; }

        private void cb_BaudRateSelectedChanged()
        {
            if (cb_BaudRateSelectItem != null)
            {
                BaudRate = Convert.ToInt32(cb_BaudRateSelectItem.ToString());
                settings.cSerialEntity.BaudRate = BaudRate;
            }
        }

        private string _connectedStateBrush = "Gray";

        public string ConnectedStateBrush
        {
            get { return _connectedStateBrush; }
            set { SetProperty(ref _connectedStateBrush, value); }
        }

        public DelegateCommand OpenComCommand
        { get { return new DelegateCommand(OpenCom).ObservesCanExecute(() => OpenComEnabled); } }

        public DelegateCommand CloseComCommand
        { get { return new DelegateCommand(CloseCom).ObservesCanExecute(() => ComIsEnabled); } }

        private void OpenCom()
        {
            settings.cSerialEntity.BaudRate = BaudRate;
            settings.cSerialEntity.PortName = ComName;
            cLed.SerialPortManager.CurrentSerialSettings = settings;
            bool ret = cLed.OpenCom(ComName, Convert.ToInt32(BaudRate));
            if (false == ret)
            {
                LogMessage("串口打开失败！");
                return;
            }
            if (cLed.SerialPortManager.IsOpen == true)
            {
                ConnectedStateBrush = "Green";
                ComIsEnabled = true;
                OpenComEnabled = false;
            }
            else
            {
                ConnectedStateBrush = "Gray";
                OpenComEnabled = true;
                ComIsEnabled = false;
            }
            LogMessage("串口打开成功！");
        }

        private void CloseCom()
        {
            try
            {
                if (cLed.SerialPortManager.IsOpen == true)
                {
                    cLed.SerialPortManager.CloseCom();
                }
                if (cLed.SerialPortManager.IsOpen == true)
                {
                    ConnectedStateBrush = "Green";
                    ComIsEnabled = true;
                }
                else
                {
                    ConnectedStateBrush = "Gray";
                    ComIsEnabled = false;
                }
            }
            catch (Exception e)
            {
                LogMessage("关闭串口出现异常：" + e.Message);
            }
            OpenComEnabled = true;
            ComIsEnabled = false;
        }

        public DelegateCommand SaveComCommand
        {
            get { return new DelegateCommand(SaveCom); }//.ObservesCanExecute(() => ComIsEnabled);
        }

        private void SaveCom()
        {
            if ((ComName.Length > 0) && (BaudRate > 0))
            {
                settings.cSerialEntity.BaudRate = BaudRate;
                settings.cSerialEntity.PortName = ComName;
                cLed.SerialPortManager.CurrentSerialSettings = settings;
                cLed.SaveComParam();
                LogMessage("串口参数保存成功！");
            }
            else
            {
                LogMessage("串口参数保存失败！");
            }
        }

        #endregion Com name   Process

        #region mcu control led commmand

        private string _deviceAdress;

        public string DeviceAdress
        {
            get { return _deviceAdress; }
            set { SetProperty(ref _deviceAdress, value); }
        }

        private ObservableCollection<ObservableCollection<string>> _obtnBrushes;

        public ObservableCollection<ObservableCollection<string>> obtnBrushes
        {
            get { return _obtnBrushes; }
            set { SetProperty(ref _obtnBrushes, value); }
        }

        public DelegateCommand ReadAdressCommand { get; set; }
        public DelegateCommand WriteAdressCommand { get; set; }

        public DelegateCommand<object> BtnClickCommand
        {
            get { return new DelegateCommand<object>(BtnClick).ObservesCanExecute(() => ComIsEnabled); }
        }

        private void ReadAdress()
        {
            try
            {
                string deviceAdress = "";
                cLed.ReadDeviceID(ref deviceAdress);
                DeviceAdress = deviceAdress;
                LogMessage("读取设备地址完成！");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void WriteAdress()
        {
            if (DeviceAdress.Length == 9)
            {
                cLed.SetDeviceAdress(DeviceAdress);
                LogMessage("执行写入动作完成！");
            }
        }

        private byte Not(byte oldv)
        {
            if (0 == oldv)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        private void BtnClick(object button)
        {
            Button btn = (Button)button;
            int col = Convert.ToInt32(btn.Content);
            string btnName = btn.Name;
            int row = Convert.ToInt32(btnName.Substring(3, 1));
            LED[row, col] = Not(LED[row, col]);
            cLed.OpenLED(DeviceAdress, LED);
            if (0 == LED[row, col])
            {
                obtnBrushes[row][col] = "Green";//绿色
            }
            else
            {
                obtnBrushes[row][col] = "Gray";//灰色
            }
            btn.Focusable = false;
        }

        //private void Navigate()
        //{
        //    var parameters = new NavigationParameters();
        //    parameters.Add("ComBase", cLed);
        //    if (cLed != null)
        //    {
        //        string navigatePath = "PUC_OpenCom";
        //        _regionManager.RequestNavigate("ComContentRegion", navigatePath, parameters);
        //    }
        //}
        public DelegateCommand OpenAllCommand
        {
            get { return new DelegateCommand(OpenAll).ObservesCanExecute(() => ComIsEnabled); }//.ObservesCanExecute(() => IsEnabled);
        }

        private void OpenAll()
        {
            cLed.OpenAllLED();
        }

        public DelegateCommand CloseAllCommand
        {
            get { return new DelegateCommand(CloseAll).ObservesCanExecute(() => ComIsEnabled); }//.ObservesCanExecute(() => IsEnabled);
        }

        private void CloseAll()
        {
            cLed.CloseAllLED();
        }

        #endregion mcu control led commmand

        #region initialize led

        private void Initialize()
        {
            _obtnBrushes = new ObservableCollection<ObservableCollection<string>>();

            for (int row = 0; row < 6; row++)
            {
                ObservableCollection<string> rowled = new ObservableCollection<string>();
                for (int col = 0; col < 8; col++)
                {
                    rowled.Add("Gray");
                }
                obtnBrushes.Add(rowled);
            }
            for (int ii = 0; ii < MaxRow; ii++)                        //输出方法一
            {
                for (int j = 0; j < MaxCol; j++)
                {
                    LED[ii, j] = 1;
                }
            }

            string str = obtnBrushes[0][0];
        }

        #endregion initialize led
    }
}